package response;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/ajax-response")
public class AjaxJsonServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Message> messageList = new ArrayList<>();
        Message m1 = new Message("咪咪","旺财","来吃小鱼干");
        Message m2 = new Message("旺财","咪咪","来吃小骨头");
        messageList.add(m1);
        messageList.add(m2);
        ObjectMapper mapper = new ObjectMapper();
        //把java对象转换为一个json字符串。list和数组会转换为[]，一个对象{成员变量名：值}
        String json = mapper.writeValueAsString(messageList);
        //{"form":"旺财","to":"咪咪","info":"来吃小鱼干"},{"form":"旺财","to":"咪咪","info":"来吃小骨头"}
        System.out.println("转换的json字符串" + json);

        //设置json可以不设置Content-Length.tomcat会设置
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().println(json);
    }

    static class Message{
        private String from;//谁
        private String to;//对谁
        private String info;//说了什么

        public Message(String from, String to, String info) {
            this.from = from;
            this.to = to;
            this.info = info;
        }

        public String getForm() {
            return from;
        }

        public void setForm(String from) {
            this.from = from;
        }

        public String getTo() {
            return to;
        }

        public void setTo(String to) {
            this.to = to;
        }

        public String getInfo() {
            return info;
        }

        public void setInfo(String info) {
            this.info = info;
        }
    }
}
